<template>
  <div class="container" ref="container"></div>
</template>

<script>
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

export default {
  name: 'SteelTemperatureMap',
  data() {
    return {
      scene: null,
      camera: null,
      renderer: null,
      steel: null,
      raycaster: null,
      mouse: new THREE.Vector2(),
      controls: null,
      temperatureData: [], // 存储温度数据
      hoverInfo: null // 存储悬停信息
    };
  },
  mounted() {
    this.initScene();
    this.createSteelModel();
    this.animate();
    window.addEventListener('resize', this.onWindowResize);
    this.$refs.container.addEventListener('mousemove', this.onMouseMove, false);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onWindowResize);
    this.$refs.container.removeEventListener('mousemove', this.onMouseMove);
  },
  methods: {
    initScene() {
      // 创建场景
      this.scene = new THREE.Scene();
      this.scene.background = new THREE.Color(0xf0f0f0);

      // 创建相机
      const width = this.$refs.container.clientWidth;
      const height = this.$refs.container.clientHeight;
      this.camera = new THREE.PerspectiveCamera(60, width / height, 0.1, 1000);
      this.camera.position.set(5, 5, 5);
      this.camera.lookAt(0, 0, 0);

      // 创建渲染器
      this.renderer = new THREE.WebGLRenderer({ antialias: true });
      this.renderer.setSize(width, height);
      this.renderer.setPixelRatio(window.devicePixelRatio);
      this.$refs.container.appendChild(this.renderer.domElement);

      // 添加轨道控制器
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      this.controls.enableDamping = true;
      this.controls.dampingFactor = 0.05;

      // 添加光源
      const ambientLight = new THREE.AmbientLight(0x404040);
      this.scene.add(ambientLight);

      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
      directionalLight.position.set(1, 1, 1);
      this.scene.add(directionalLight);

      // 初始化射线检测
      this.raycaster = new THREE.Raycaster();

      // 添加坐标轴辅助
      const axesHelper = new THREE.AxesHelper(5);
      this.scene.add(axesHelper);
    },

    createSteelModel() {
      // 钢坯尺寸 (长x宽x高)
      const length = 4, width = 2, height = 1;

      // 创建钢坯几何体
      const geometry = new THREE.BoxGeometry(length, width, height, 396, 1, 20);

      // 生成温度数据 (模拟数据)
      this.generateTemperatureData(geometry);

      // 创建材质
      const material = new THREE.MeshPhongMaterial({
        vertexColors: true,
        side: THREE.DoubleSide,
        flatShading: true,
        shininess: 100
      });

      // 创建钢坯网格
      this.steel = new THREE.Mesh(geometry, material);
      this.scene.add(this.steel);

      // 添加线框辅助查看网格
      const wireframe = new THREE.LineSegments(
          new THREE.EdgesGeometry(geometry),
          new THREE.LineBasicMaterial({ color: 0x000000, transparent: true, opacity: 0.2 })
      );
      this.steel.add(wireframe);
    },

    generateTemperatureData(geometry) {
      // 模拟温度数据 (0-1000°C)
      const positions = geometry.attributes.position;
      const colors = [];
      this.temperatureData = [];

      for (let i = 0; i < positions.count; i++) {
        const x = positions.getX(i);
        const y = positions.getY(i);
        const z = positions.getZ(i);

        // 模拟温度分布 (中心温度高，边缘温度低)
        const distanceToCenter = Math.sqrt(x*x + y*y + z*z);
        const temp = 1000 - distanceToCenter * 150;
        const normalizedTemp = Math.max(0, Math.min(1, temp / 1000));

        // 存储温度数据
        this.temperatureData.push({
          position: new THREE.Vector3(x, y, z),
          temperature: temp
        });

        // 根据温度设置颜色 (冷色到暖色)
        colors.push(this.getTemperatureColor(normalizedTemp));
      }

      // 设置顶点颜色
      geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
    },

    getTemperatureColor(normalizedTemp) {
      // 温度颜色映射 (蓝色->青色->黄色->红色)
      const color = new THREE.Color();
      if (normalizedTemp < 0.25) {
        color.r = 0;
        color.g = normalizedTemp * 4;
        color.b = 1;
      } else if (normalizedTemp < 0.5) {
        color.r = 0;
        color.g = 1;
        color.b = 1 - (normalizedTemp - 0.25) * 4;
      } else if (normalizedTemp < 0.75) {
        color.r = (normalizedTemp - 0.5) * 4;
        color.g = 1;
        color.b = 0;
      } else {
        color.r = 1;
        color.g = 1 - (normalizedTemp - 0.75) * 4;
        color.b = 0;
      }
      return [color.r, color.g, color.b];
    },

    onMouseMove(event) {
      // 计算鼠标在归一化设备坐标中的位置 (-1到+1)
      const rect = this.$refs.container.getBoundingClientRect();
      this.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
      this.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;

      // 更新射线
      this.raycaster.setFromCamera(this.mouse, this.camera);

      // 计算与钢坯的交点
      const intersects = this.raycaster.intersectObject(this.steel);

      if (intersects.length > 0) {
        const intersect = intersects[0];

        // 找到最近的温度数据点
        let closestPoint = null;
        let minDistance = Infinity;

        for (const data of this.temperatureData) {
          const distance = data.position.distanceTo(intersect.point);
          if (distance < minDistance) {
            minDistance = distance;
            closestPoint = data;
          }
        }

        // 显示温度信息
        if (closestPoint) {
          this.hoverInfo = {
            position: closestPoint.position,
            temperature: closestPoint.temperature.toFixed(1) + '°C'
          };

          // 这里可以添加显示温度信息的UI逻辑
          console.log(`位置: (${closestPoint.position.x.toFixed(2)}, ${closestPoint.position.y.toFixed(2)}, ${closestPoint.position.z.toFixed(2)}), 温度: ${closestPoint.temperature.toFixed(1)}°C`);
        }
      } else {
        this.hoverInfo = null;
      }
    },

    onWindowResize() {
      const width = this.$refs.container.clientWidth;
      const height = this.$refs.container.clientHeight;

      this.camera.aspect = width / height;
      this.camera.updateProjectionMatrix();
      this.renderer.setSize(width, height);
    },

    animate() {
      requestAnimationFrame(this.animate);
      this.controls.update();
      this.renderer.render(this.scene, this.camera);
    }
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.tooltip {
  position: absolute;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 3px;
  pointer-events: none;
}
</style>